#include <iostream>
#include <string>
#include <unistd.h>
#include "Sock.hpp"
#include "Protocol.hpp"
#include "Log.hpp"

int main()
{
    Sock sock;
    sock.CreateClient(8080,"127.0.0.1");
    int sockfd=sock.Fd();
    bool quit=false;
    std::string content;
    while(!quit)
    {
        Request request;
        std::cin>>request._x>>request._op>>request._y;
        std::string messages=request.Serialization();//序列化
        std::string res=Encode(messages);//封包
        send(sockfd,res.c_str(),res.size(),0);
        char buffer[1024];
        bzero(buffer,sizeof(buffer));
        while(true)
        {
            ssize_t s=recv(sockfd,buffer,sizeof(buffer)-1,0);
            if(s>0)
            {
                buffer[s]='\0';
                content+=buffer;
                std::string package=Decode(content);
                if(package.empty()) continue;
                //获取到了完整的数据
                Response response;
                response.Deserialization(package);
                int flag=response._code;
                std::string err;
                switch(flag)
                {
                    case 1:
                        err="除零错误";
                        break;
                    case 2:
                        err="模零错误";
                        break;
                    case 3:
                        err="非法错误";
                        break;
                    case 0:
                        printf("%d%c%d=%d\n",request._x,request._op,request._y,response._result);
                        break;
                    default :
                        err="未知错误";
                        break;
                }
                if(!err.empty()) LogMessage(ERROR,"%s\n",err.c_str());
                break;
            }
            else if(s==0)
            {
                LogMessage(NORMAL,"server aside,me too.....\n");
                quit=true;
                break;
            }
            else
            {
                LogMessage(ERROR,"client recv error.....\n");
                quit=true;
                break;
            }
        }
    }
    close(sockfd);
    return 0;
}